<template>
    <div style="margin-left: auto">
        <p>采购入库</p>
    </div>
    <div>
        <span style="float: right;">
            <el-button type="primary" @click="addPurchaseInvoice">保存</el-button>
            <el-button type="Default" @click="">取消</el-button>
            <el-button style="background-color: aquamarine;border-color: aquamarine;color: white;"
                @click="">审核</el-button>
            <el-button type="info" @click="">反审核</el-button>
        </span>
    </div>
    <hr />
    <el-scrollbar style="height: 320px; color: dimgray">
        <div class="scrollbar-flex-content">
            <p class="scrollbar-demo-item">
                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="单据编码：" style="width: 308px">
                        <el-input v-model="form.documentNumber" :disabled="true" />
                    </el-form-item>
                    <el-form-item label="单据日期" style="width: 308px">
                        <el-date-picker v-model="form.documentDate" disabled="true" type="date" style="width: 100%" />
                    </el-form-item>
                    <el-form-item label="单据状态" style="width: 308px">
                        <el-select v-model="form.documentStatus" disabled="true">
                            <el-option label="开立" value="开立" />
                            <el-option label="审核" value="审核" />
                            <el-option label="返回" value="返回" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="单据类型" style="width: 308px">
                        <el-select v-model="form.documentType" placeholder="请选择" disabled="true">
                            <el-option label="入库单" value="入库单" />
                        </el-select>
                    </el-form-item>

                </el-form>

                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="业务类型" style="width: 308px">
                        <el-select v-model="form.businessType" placeholder="请选择" disabled="true">
                            <el-option label="采购入库" value="采购入库" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务状态" style="width: 308px">
                        <el-select v-model="form.businessStatus" placeholder="请选择" disabled="true">
                            <el-option label="正常" value="正常" />
                            <el-option label="挂起" value="挂起" />
                            <el-option label="手工关闭" value="手工关闭" />
                            <el-option label="系统关闭" value="系统关闭" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务部门：" style="width: 308px">
                        <el-select v-model="form.businessUnit">
                            <el-option label="总经办" value="1" />
                            <el-option label="市场部" value="2" />
                            <el-option label="采购部" value="3" />
                            <el-option label="销售部" value="4" />
                            <el-option label="生产运营中心" value="5" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务人员：" style="width: 308px">
                        <el-select v-model="form.businessPersonnel">
                            <el-option label="赵多和" value="赵多和" />
                            <el-option label="姜楠" value="姜楠" />
                        </el-select>
                    </el-form-item>

                </el-form>

                <el-form :inline="true" style="margin-top: 50px;" :model="form" class="demo-form-inline">
                    <el-form-item label="操作员" style="width: 308px">
                        <el-input v-model="form.operatorName" :disabled="true" />
                    </el-form-item>
                    <el-form-item label="供应商" style="width: 308px">
                        <el-input v-model="form.supplier" />
                        <el-link type="primary" @click="dialogTableVisibleGYS = true">选择</el-link>
                    </el-form-item>
                    <el-form-item label="期间：" style="width: 308px">
                        <el-date-picker v-model="form.period" type="date" />
                    </el-form-item>

                    <div>
                        <el-dialog v-model="dialogTableVisibleGYS" title="选择物料" width="900" style="height: 600px">
                            <el-form :inline="true" :model="formInline" class="demo-form-inline">
                                <el-form-item label="供应商名称">
                                    <el-input v-model="formInline.supplierName" placeholder="请输入供应商名称" clearable />
                                </el-form-item>
                                <el-form-item label="业务联系人">
                                    <el-input v-model="formInline.businessContact" placeholder="请输入业务联系人" clearable />
                                </el-form-item>
                                <el-form-item label="供应料品">
                                    <el-select v-model="formInline.materialTypeName" placeholder="请选择" clearable
                                        style="width: 150px;">
                                        <el-option v-for="item in material" :key="item.materialTypeId"
                                            :label="item.materialTypeName" :value="item.materialTypeId" />
                                    </el-select>
                                </el-form-item>


                                <el-form-item>
                                    <el-button type="primary" @click="GetSuppliers()">搜索</el-button>
                                </el-form-item>


                            </el-form>
                            <el-button type="primary" :icon="List" @click="GetSuppliers1()">查询所有</el-button>



                            <el-empty description="暂无数据" v-show="suppliers.length == 0" />
                            <el-table :data="suppliers" stripe style="width: 100%" v-show="suppliers.length != 0">
                                <el-table-column prop="supplierId" label="序号" />
                                <el-table-column prop="supplierName" label="供应商名称" />
                                <el-table-column prop="supplierAbbreviation" label="简称" />
                                <el-table-column prop="companyAddress" label="公司地址" />
                                <el-table-column prop="phone" label="电话" />
                                <el-table-column prop="businessContact" label="业务联系人" />
                                <el-table-column prop="materialTypeName" label="供应料品" />
                                <el-table-column label="操作">
                                    <template #default="scope">
                                        <el-link type="primary" @click="xzgys(scope.row)">选择</el-link> &nbsp;
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div>
                                <tr>
                                    <td>
                                        <el-pagination v-model:current-page="formInline.pageIndex"
                                            v-model:page-size="formInline.pageSize" :page-sizes="[10, 20, 30, 40, 50]"
                                            :background="true" layout="total, slot, prev, pager, next"
                                            :total="formInline.totalCount" @size-change="handleSizeChange"
                                            @current-change="handleCurrentChange">
                                        </el-pagination>
                                    </td>
                                    <td>
                                        <el-pagination v-model:current-page="formInline.pageIndex"
                                            v-model:page-size="formInline.pageSize" :page-sizes="[10, 20, 30, 40, 50]"
                                            :background="true" layout="slot, sizes, jumper"
                                            :total="formInline.totalCount" @size-change="handleSizeChange"
                                            @current-change="handleCurrentChange">
                                        </el-pagination>
                                    </td>
                                </tr>
                            </div>
                        </el-dialog>
                    </div>
                </el-form>

                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="仓库" style="width: 308px">
                        <el-select v-model="form.warehouseId" disabled="true">
                            <el-option label="成品仓" value="成品仓" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="到货单号" style="width: 308px">
                        <el-input v-model="form.trackingNumber" />
                    </el-form-item>
                    <el-form-item label="备注信息" style="width: 308px">
                        <el-input v-model="form.noteInformation" />
                    </el-form-item>


                </el-form>
            </p>
        </div>
    </el-scrollbar>
    <div style="float: right;">
        <el-button type="warning" @click="">¼ 引入</el-button>
        <el-button type="primary" @click="addMaterial">新增物料</el-button>

    </div>

    <table style="border-collapse: collapse">
        <tr>
            <td>序号</td>
            <td>销售订单号</td>
            <td>物料编码</td>
            <td>物料名称</td>
            <td>型号规格</td>
            <td>主计量</td>
            <td>数量</td>
            <td>体积</td>
            <td>批号</td>
            <td>备注</td>
            <td>操作</td>
        </tr>
        <tr v-for="(ruleForm, index) in loge.healthArray">
            <td>
                {{ ruleForm.purchaseIncomingMaterialsId }} <!-- 序号 -->
            </td>
            <td>
                {{ ruleForm.salesOrder }} <!-- 销售订单号 -->
            </td>
            <td>
                {{ ruleForm.itemBianma }} <!--logisticsCode 物流编码-->
                <el-link type="primary" @click="xuanz(index)">选择</el-link>
                <div>
                    <el-dialog v-model="dialogTableVisibleWl" title="选择物料" width="900" style="height: 600px">
                        <div class="common-layout" style="width: 165px; float: left">
                            <el-container>
                                <el-aside width="165px" style="margin-left: 10px">
                                    <el-tree ref="treeRef" class="filter-tree" :data="data" :props="defaultProps" style="
                      width: 165px;
                      border: 0px solid #ccc;
                      float: left;
                      height: 500px;
                    " default-expand-all :expand-on-click-node="false" :filter-node-method="filterNode"
                                        @node-click="handleNodeClick" />
                                </el-aside>
                                <el-main> </el-main>
                            </el-container>
                        </div>
                        <div class="common-layout" style="float: right; top: 12px">
                            <el-form :inline="true" :model="page" class="demo-form-inline">
                                <el-form-item label="物料编码">
                                    <el-input v-model="Materials.itemBianma" />
                                </el-form-item>
                                <el-form-item label="物料名称">
                                    <el-input v-model="Materials.itemName" />
                                </el-form-item>
                                <el-button type="primary" @click="SearchMaterialsShow">搜索</el-button>
                            </el-form>
                            <el-table :data="MaterialsShowlist" style="height: 500px">
                                <el-table-column property="itemBianma" label="物料编码" width="150" />
                                <el-table-column property="itemName" label="物料名称" width="200" />
                                <el-table-column property="modelspecification" label="型号规格" />
                                <el-table-column property="measureId" label="主计量" />
                                <el-table-column label="操作">
                                    <template #default="scope">
                                        <el-button type="primary"
                                            @click="Selectnumber(scope.row.itemBianma, scope.row.itemName, scope.row.modelspecification, scope.row.measureId, index1)">选择</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-dialog>
                </div>
            </td>
            <td>{{ ruleForm.materialName }}</td><!--nameOfLogistics 物料名称 -->
            <td>{{ ruleForm.typeSpecification }}</td><!--modelSpecification 型号规格 -->
            <td>{{ ruleForm.documentType }}</td><!--mainMetering 主计量 -->
            <td>
                <el-input v-model="ruleForm.quantity" placeholder="请输入数量" style="width: 100px"></el-input>
            </td><!--num 数量 -->
            <td><el-input v-model="ruleForm.volume" style="width: 100px"></el-input></td>
            <td><el-input v-model="ruleForm.lotNumber" style="width: 100px"></el-input></td>
            <td><el-input v-model="ruleForm.remark" style="width: 100px"></el-input></td>
            <!-- 税额 -->
            <td>
                <el-button type="danger" link @click="del">删除</el-button>
            </td>
        </tr>
    </table>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import Cookie from 'cookies-ts';
import axios from 'axios';
import { number } from 'echarts';
const cookie = new Cookie()
import { Plus, Download, Upload, List } from '@element-plus/icons-vue'
const dialogFormVisiblePDF: any = ref(false);
const dialogTableVisible: any = ref(false);
const dialogFormVisibleXML: any = ref(false);
const dialogFormVisibleOFD: any = ref(false);
const dialogTableVisibleWl: any = ref(false)
const dialogTableVisibleGYS: any = ref(false)
const apiurls = import.meta.env.VITE_APP_API_URL_BasicInformationCommon;//5176
const bpiurls = import.meta.env.VITE_APP_API_URL_BasicInformationWrite;//5013
const cpiurls = import.meta.env.VITE_APP_API_URL_RBACCommon;//5214
const dpiurls = import.meta.env.VITE_APP_API_URL_RBACWrite;//5268
const epiurls = import.meta.env.VITE_APP_API_URL_SalesManagementCommon;//5227
const fpiurls = import.meta.env.VITE_APP_API_URL_SalesManagementWrite;//5020
const formLabelWidth = '140px';

onMounted(() => {
    GetBang();
    SearchMaterialsShow()
    getMaterial()
    GetSuppliers()
    GetSuppliers1()
    loadData()
});

const form = reactive({
    "documentNumber": JSON.stringify(new Date().getTime()),
    "documentDate": new Date(),
    "documentStatus": "开立",
    "documentType": "入库单",
    "businessType": "采购入库",
    "businessStatus": "正常",
    "businessUnit": 0,
    "businessPersonnel": "",
    "operatorName": "",
    "period": new Date(),
    "warehouseId": "成品仓",
    "trackingNumber": "",
    "supplier": "",
    "noteInformation": ""
});

const numbers = ref(1)
const loge = reactive({
    healthArray: <any>[
        reactive({
            purchaseIncomingMaterialsId: numbers.value,
            salesOrder: "手工单据",
            itemBianma: "",
            materialName: "",
            typeSpecification: "",
            documentType: "",
            quantity: 0,
            volume: "",
            lotNumber: "",
            remark: "",
            serialNumber: ""
        })
    ]

});
//新增行
const addMaterial = () => {
    loge.healthArray.push(reactive({
        purchaseIncomingMaterialsId: loge.healthArray.length + numbers.value,
        salesOrder: "手工单据",
        itemBianma: "",
        materialName: "",
        typeSpecification: "",
        documentType: "",
        quantity: 0,
        volume: "",
        lotNumber: "",
        remark: "",
        serialNumber: ""
    }))
}
//删除行
const del = () => {
    loge.healthArray.splice(loge.healthArray.length - 1, 1)
    ElMessage.warning({
        message: '删除成功',
    })
}
//选择物料
const uptform = reactive({
    materialTypeName: '',
    pId: 0,
})
const filterNode = (value: string, data: any) => {
    if (!value) return true;
    return data.label.includes(value);
};
//树形级联
const defaultProps = {
    children: 'children',
    label: 'label',
}
var data = ref([])
function GetBang() {
    axios({
        url: apiurls + '/api/Materials/GetmaterialTree',
        method: 'get'
    })
        .then((res) => {
            data.value = res.data.data
        })
}

const handleNodeClick = (data: any) => {

    uptform.materialTypeName = data.label
    uptform.pId = data.value
    console.log(uptform.pId)
}
const page = reactive({
    customerName: "",
    businessContacts: "",
    PageIndex: 1,
    PageSize: 100,
    totalCount: 0,
    pageCount: 0,
})
const Materials = reactive({
    itemBianma: "",
    itemName: ""
})

const MaterialsShowlist = ref([])
const SearchMaterialsShow = () => {
    axios.get(apiurls + '/api/Materials/MaterialesSearch', {
        params: {
            materialTypeId: uptform.pId,
            itemBianma: Materials.itemBianma,
            itemName: Materials.itemName
        }
    }).then((res) => {
        MaterialsShowlist.value = res.data.data2
        console.log(MaterialsShowlist.value);
    })
}
const index1 = ref(0)
const xuanz = (index: any) => {
    dialogTableVisibleWl.value = true
    index1.value = index
}
//映射用户名到操作员文本框里
const loadData = () => {
    if (cookie.get('employeeName') != null) {
        form.operatorName = cookie.get('employeeName') as string
    }
}
const Selectnumber = (itemBianma: any, materialName: any, typeSpecification: any, measureId: any, index: any) => {
    console.log(index)
    localStorage.setItem('itemBianma', itemBianma)
    localStorage.setItem('itemName', materialName)
    localStorage.setItem('modelspecification', typeSpecification)
    localStorage.setItem('measureId', measureId)
    if (localStorage.getItem('itemBianma') != null || localStorage.getItem('itemName') != null || localStorage.getItem('modelspecification') != null || localStorage.getItem('measureId') != null) {
        loge.healthArray[index].itemBianma = localStorage.getItem('itemBianma') as string
        loge.healthArray[index].materialName = localStorage.getItem('itemName') as string
        loge.healthArray[index].typeSpecification = localStorage.getItem('modelspecification') as string
        loge.healthArray[index].documentType = localStorage.getItem('measureId') as string
    }
    console.log(loge.healthArray[index])
    dialogTableVisibleWl.value = false
}

const addPurchaseInvoice = () => {
    axios.post(bpiurls + '/api/PurchaseWarehousing/CreatePurchaseIncomingMaterials', form).then(res => {
        if (res.data.code == 0) {
            ElMessage.success(res.data.msg)
        }
        else {
            ElMessage.error(res.data.msg)
        }
    })
    const request: any = ref({});
    request.IncomingMaterials = loge.healthArray;
    axios.post(bpiurls + '/api/PurchaseWarehousing/CreatePurchaseIncomingMaterialsBatch', request)
        .then(res => {
            if (res.data.code == 0) {
                ElMessage.success(res.data.msg)
            }
            else {
                ElMessage.error(res.data.msg)
            }
        })
}

//供应商
const formInline = reactive({
    supplierName: '',
    businessContact: '',
    materialTypeName: '',
    pageIndex: 1,
    pageSize: 10,
    pageCount: 0,
    totalCount: 0,

})

//供应商列表
const suppliers: any = ref([]);
const GetSuppliers = () => {
    axios
        .get(
            apiurls + '/api/Suppliers/SuppliersList',
            {
                params: {
                    supplierName: formInline.supplierName,
                    businessContact: formInline.businessContact,
                    materialTypeName: formInline.materialTypeName || 0,
                    pageIndex: formInline.pageIndex,
                    pageSize: formInline.pageSize,
                }
            }
        )
        .then((res) => {
            console.log(res.data.data);
            suppliers.value = res.data.data;
            formInline.pageCount = res.data.pageCount;
            formInline.totalCount = res.data.totalCount;
        })
        .catch((err) => {
            console.log(err);
        });
};

const GetSuppliers1 = () => {
    axios
        .get(
            apiurls + '/api/Suppliers/SuppliersList',
            {
                params: {
                    supplierName: '',
                    businessContact: '',
                    materialTypeName: 0,
                    pageIndex: formInline.pageIndex,
                    pageSize: formInline.pageSize,
                }
            }
        )
        .then((res) => {
            console.log(res.data.data);
            suppliers.value = res.data.data;
            formInline.pageCount = res.data.pageCount;
            formInline.totalCount = res.data.totalCount;
        })
        .catch((err) => {
            console.log(err);
        });
};

//分页
const handleSizeChange = (val: number) => {
    formInline.pageSize = val
    GetSuppliers()
}
const handleCurrentChange = (val: number) => {
    formInline.pageIndex = val
    GetSuppliers()
}
//物料下拉框
const material: any = ref([]);
const getMaterial = () => {
    axios
        .get(apiurls + '/api/Suppliers/MaterialList')
        .then((res) => {
            console.log(res.data.data);
            material.value = res.data.data;
        })
        .catch((err) => {
            console.log(err);
        });
};
//选择供应商
const xzgys = (row: any) => {
    form.supplier = row.supplierName
    dialogTableVisibleGYS.value = false
}

</script>
<style scoped>
.scrollbar-flex-content {
    display: flex;
}

.scrollbar-demo-item {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 1500px;
    height: 300px;
    margin: 10px;
    text-align: center;
    border-radius: 4px;
}
</style>
<style scoped>
.demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
}

.demo-pagination-block .demonstration {
    margin-bottom: 16px;
}

/* 设置第一行的 td 顶部边框加粗并设置为红色 */
table tr:first-child td {
    border-top: 1px solid #ccc;
    /* 设置顶部边框为3px宽度的红色 */
    padding: 10px;
    text-align: center;
}

/* 设置 td 的样式 */

table td {
    padding: 10px;
    border: 1px solid #ccc;
    text-align: center;
    font-size: 14px;
    height: 60px;
    width: 150px;
    white-space: nowrap;
    /* 防止内容换行 */
}

/* 可选：为 table 添加样式 */
table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
}

/*______________________________________________________*/

.table-container {
    max-width: 100%;
    overflow-x: auto;
    /* 启用水平滚动 */
    margin: 20px 0;
    /* 设置容器的外边距 */
}

/* :deep(.el-input__wrapper) {
    box-shadow: none;
    text-align: center;
}

:deep(.el-select__wrapper) {
    box-shadow: none;
}

::v-deep(.center-input .el-input__inner) {
    text-align: center;
} */
</style>
